package ysutils

import (
	"context"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/text/gstr"
)

// RunSql 执行 sql 语句, 执行异常时返回值为 error
func RunSql(ctx context.Context, sql string, name ...string) error {
	group := "default"
	
	logger := g.Log().Clone()
	logger.SetPrefix("[ys-ts.utils.db]")
	
	if len(name) > 0 {
		group = name[0]
	}
	
	lines := gstr.SplitAndTrim(sql, ";")
	total := len(lines)
	skip := 0
	logger.Infof(ctx, "总共需要执行：%d 条语句", total)
	for index, line := range lines {
		
		// 去除只有注释的行
		if gstr.HasPrefix(line, "--") && !gstr.Contains(line, "\n") {
			skip += 1
			continue
		}
		
		_, err := g.DB(group).Exec(ctx, line)
		if err != nil {
			return gerror.NewCode(gcode.WithCode(gcode.CodeDbOperationError, err), err.Error())
		}
		logger.Infof(ctx, "进度： %d / %d", index+1, total)
	}
	logger.Infof(ctx, "执行: %d 跳过: %d", total-skip, skip)
	return nil
	
}

// RunSqlFromFile 通过文件执行 sql 语句。<path> 指代文件路径
func RunSqlFromFile(ctx context.Context, path string, name ...string) error {
	if !gfile.Exists(path) {
		return gerror.NewCodef(gcode.CodeInvalidParameter, "路径不存在 %s", path)
	}
	
	sql := gfile.GetContents(path)
	return RunSql(ctx, sql, name...)
}
